import { ActionContext } from 'vuex'
import db from '@/components/db'
import { Order, OrderState } from '@/models/Order';
import _ from 'lodash';

interface State {
    orders: Order[],
    totalPrice: number,
    noticeOrderList: Order[]
}

const initState = {
    orders: [],
    totalPrice: 0,
    noticeOrderList: []
}

const getters = {
    orders(state: State) {
        return state.orders
    },
    validOrders(state: State) {
        return _.filter(state.orders, (item) => {
            return item.state !== OrderState.invalid;
        })
    },
    invalidOrders(state: State) {
        return _.filter(state.orders, (item) => {
            return item.state === OrderState.invalid;
        })
    },
    totalPrice(state: State) {
        return state.totalPrice
    },
    noticeOrders(state: State) {
        return state.noticeOrderList
    },
    outdateOrders(state: State) {
        return _.filter(state.orders, (item) => {
            return item.state === OrderState.outdate;
        })
    },
    finishOrders(state: State) {
        return _.filter(state.orders, (item) => {
            return item.state === OrderState.finished;
        })
    },
    presaleNoticeList(state: State) {
        return _.filter(state.orders, (item) => {
            return item.presaleNoticeList;
        })
    }
}

const actions = {
    initOrders(context: ActionContext<State, any>) {
        return new Promise((resolve, reject) => {
            db.filter('order').then((orders) => {
                let arr: Order[] = [];
                if (orders instanceof Array) {
                    if (orders.length > 0) {
                        orders.forEach(item => {
                            const o = new Order(item);
                            if (o.isNoticeOrder()) {
                                context.state.noticeOrderList.push(o);
                            }
                            arr.push(o);
                        })
                    }
                }
                context.commit('initOrders', arr);
                resolve();
            }).catch(reason => {
                reject(reason);
            })
        })
    },
    filterOrders(context: ActionContext<State, any>, filter: any) {
        return new Promise((resolve, reject) => {
            db.filter('order', filter).then((orders) => {
                let arr: Order[] = [];
                if (orders instanceof Array) {
                    if (orders.length > 0) {
                        orders.forEach(item => {
                            const o = new Order(item);
                            arr.push(o);
                        })
                        resolve(arr);
                    } else {
                        reject(new Error('没有找到相关订单'))
                    }
                } else {
                    reject(new Error('没有找到相关订单'))
                }
            }).catch(reason => {
                reject(reason);
            })
        })
    },
    getOrderById(context: ActionContext<State, any>, orderid: string) {
        return new Promise((resolve, reject) => {
            let o = _.find(context.state.orders, { id: orderid });
            if (o) {
                resolve(o)
            } else {
                reject(new Error("找不到订单"))
            }
        })
    },
    addOrder(context: ActionContext<State, any>, order: Order) {
        return new Promise((resovle, reject) => {
            db.insert('order', order).then((added) => {
                context.commit('addOrder', order);
                resovle(added)
            }).catch(reason => {
                reject(reason);
            })
        })
    },
    updateOrder(context: ActionContext<State, any>, order: Order) {
        return new Promise((resolve, reject) => {
            order.update();
            db.update('order', order).then(() => {
                context.commit('updateOrder', order);
                resolve(order);
            }).catch(reason => {
                reject(reason);
            })
        })
    },
    deleteOrder(context: ActionContext<State, any>, order: Order) {
        return new Promise((resolve, reject) => {
            db.delete('order', { id: order.id }).then(result => {
                context.dispatch('increaseStock', order.product);
                context.commit('deleteOrder', order);
                resolve()
            }).catch(reason => {
                reject(reason);
            })
        })
    },
    payOrder(context: ActionContext<State, any>, payConfig: { id: string, type: string }) {
        return new Promise((resolve, reject) => {
            let o = _.find(context.state.orders, { id: payConfig.id });
            if (o) {
                if (o.state === 1) {
                    o.pay(payConfig.type);
                    context.dispatch('updateOrder', o).then(() => {
                        resolve()
                    }).catch(reason => {
                        reject(reason);
                    })
                } else {
                    reject(new Error("客户已经付款了"));
                }
            }
        })
    },
    invalidOrder(context: ActionContext<State, any>, order: Order) {
        return new Promise((resolve, reject) => {
            context.dispatch('increaseStock', order.product);
            order.invalid();
            context.dispatch('updateOrder', order).then(() => {
                resolve();
            }).catch(reason => {
                reject(reason);
            })
        })
    },
    startOrder(context: ActionContext<State, any>, order: Order) {
        return new Promise((resolve, reject) => {
            let o = _.find(context.state.orders, { id: order.id });
            if (o) {
                o.startCount();
                context.dispatch('updateOrder', o).then(() => {
                    resolve()
                }).catch(reason => {
                    reject(reason);
                })
            }
        })
    },
    finishOrder(context: ActionContext<State, any>, order: Order) {
        return new Promise((resolve, reject) => {
            let o = _.find(context.state.orders, { id: order.id });
            if (o) {
                o.finish();
                context.dispatch('updateOrder', o).then(() => {
                    resolve()
                }).catch(reason => {
                    reject(reason);
                })
            }
        })
    }
}

const mutations = {
    initOrders(state: State, orders: Order[]) {
        state.orders = orders;
        console.log("初始化的订单数据：", state.orders);
        if (state.orders.length > 0) {
            let total = 0;
            state.orders.forEach(item => {
                if (item.product && item.state !== 1 && item.state !== 0) {
                    total += item.product.price;
                }
            })
            state.totalPrice = total;
        }
    },
    addOrder(state: State, order: Order) {
        state.orders.push(order);
        if (state.orders.length > 0) {
            let total = 0;
            state.orders.forEach(item => {
                if (item.product && item.state !== 1 && item.state !== 0) {
                    total += item.product.price;
                }
            })
            state.totalPrice = total;
        }
    },
    updateOrder(state: State, order: Order) {
        let index = _.findIndex(state.orders, { id: order.id });
        if (index >= 0) {
            state.orders.splice(index, 1, order);
        }
        if (state.orders.length > 0) {
            let total = 0;
            state.orders.forEach(item => {
                if (item.product && item.state !== 1 && item.state !== 0) {
                    total += item.product.price;
                }
            })
            state.totalPrice = total;
        }
    },
    deleteOrder(state: State, order: Order) {
        let index = _.findIndex(state.orders, { id: order.id });
        if (index >= 0) {
            state.orders.splice(index, 1);
        }
    }
}

export default {
    state: initState,
    getters,
    actions,
    mutations
}